package sdu.icat.pj.sys.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import sdu.icat.pj.base.ResponseMap;
import sdu.icat.pj.service.SysNoticeService;
import sdu.icat.sys.smodel.SysNotice;

@RestController
@Api(value="notice manager",tags={"some notices managed by this controller"})
@RequestMapping("sys_notice")
public class SysNoticeController {

    @Autowired private SysNoticeService noticeService;
    
    /**
     * 发布或修改公告
     * @param notice
     * @return
     */
    @PostMapping
    @ApiOperation(value="发布/修改公告",notes="发布/修改公告，无显示操作")
    public ResponseMap pubNotice(@RequestBody SysNotice notice) {
	ResponseMap result = new ResponseMap();
	Assert.hasLength(notice.getNotice(), "NOTICE MUST HAVE CONTENT");
	Assert.isTrue(notice.getNotice().length()>100, "NOTICE IS TOO LONGER");
	noticeService.save(notice);
	result.setStatus(200);
	result.putMsg("操作成功");
	result.setData(notice);
	return result;
    }
    
    @DeleteMapping
    @ApiOperation(value="删除公告",notes="支持批量删除")
    public ResponseMap delete(Long[] ids) {
	ResponseMap result = new ResponseMap();
	Assert.noNullElements(ids, "HAS NULL ELEMENT");
	try {
	    noticeService.remove(ids);
	    result.setStatus(200);
	    result.putMsg("成功删除"+ids.length+"条公告");
	} catch (Exception e) {
	    result.setStatus(-1);
	    result.putMsg("删除失败");
	    result.setData(e);
	}
	return result;
    }
    
    @PutMapping("current")
    @ApiOperation(value="当前显示公告",notes="查看当前显示在前端的公告")
    public ResponseMap getCurrentShowNotice() {
	ResponseMap result = new ResponseMap();
	SysNotice notice = noticeService.currentShow();
	if(notice==null) {
	    result.setStatus(201);
	    result.setData(null);
	    result.putMsg("当前没有正在显示的公告");
	} else {
	    result.setStatus(200);
	    result.setData(notice);
	    result.putMsg("获取到当前公告Id:"+notice.getId());
	}
	return result;
    }
    
    @PostMapping("top")
    @ApiOperation(value="置顶显示公告")
    public ResponseMap top(@RequestBody SysNotice notice) {
	ResponseMap result = new ResponseMap();
	try {
	    noticeService.top(notice);
	    result.setStatus(200);
	    result.putMsg("置顶成功");
	    result.setData(notice);
	} catch (Exception e) {
	    result.setStatus(-1);
	    result.putMsg("置顶失败");
	    result.setData(noticeService.currentShow());
	}
	return result;
    }
    
    
}
